package com.school.controller;

import com.alibaba.cloud.ai.dashscope.api.DashScopeImageApi;
import com.alibaba.cloud.ai.dashscope.image.DashScopeImageModel;
import com.alibaba.cloud.ai.dashscope.image.DashScopeImageOptions;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.ai.image.ImagePrompt;
import org.springframework.ai.image.ImageResponse;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;

@RestController
public class ImageModelController {
    @Resource
    private DashScopeImageModel imageModel;
   @GetMapping("/image")
    public void getImageabli(@RequestParam(value = "msg",defaultValue = "生成一只王子胥")
                                  String msg, HttpServletResponse res) {
       ImageResponse response = imageModel.call(
               new ImagePrompt(
                       msg,
                       DashScopeImageOptions.builder()
                               .withModel(DashScopeImageApi.DEFAULT_IMAGE_MODEL)
                               .withN(1)
                               .withHeight(1024)
                               .withWidth(1024).build())
       );
       String imageUrl = response.getResult().getOutput().getUrl();
       try {
           URL url = URI.create(imageUrl).toURL();
           InputStream in = url.openStream();
           res.setHeader("Content-Type", MediaType.IMAGE_PNG_VALUE);
           res.getOutputStream().write(in.readAllBytes());
           res.getOutputStream().flush();
       } catch (Exception e) {

       }
   }
}
